package com.gitee.cui.basic.create;

import com.gitee.cui.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 商店线程演示，比较继承Thread和实现Runnable的优缺点
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/9 16:34
 **/
@Slf4j
public class StoreThread {

    private static final int MAX_AMOUNT = 5;

    static class StoreGoods extends Thread {

        private int goodsCount = MAX_AMOUNT;

        public StoreGoods(String threadName) {
            super(threadName);
        }

        @Override
        public void run() {
            for (int i = 0; i < MAX_AMOUNT; i++) {
                if (goodsCount > 0) {
                    log.info(ThreadUtil.getCurThreadName() + " 卖出一件，还剩：{}", --goodsCount);
                    ThreadUtil.sleepMilliSeconds(10);
                }
            }
            log.info("{} 运行结束", ThreadUtil.getCurThreadName());
        }
    }

    static class MallGoods implements Runnable {

        private AtomicInteger goodsCount = new AtomicInteger(MAX_AMOUNT);

        @Override
        public void run() {
            for (int i = 0; i < MAX_AMOUNT; i++) {
                if (goodsCount.get() > 0) {
                    log.info(ThreadUtil.getCurThreadName() +" 卖出一件，还剩：{}", goodsCount.decrementAndGet());
                    ThreadUtil.sleepMilliSeconds(10);
                }
            }
            log.info("{} 运行结束", ThreadUtil.getCurThreadName());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        log.info("商店版本销售");
        for (int i = 0; i < 2; i++) {
            StoreGoods storeGoods = new StoreGoods("店员-" + i);
            storeGoods.start();
        }
        Thread.sleep(1000);

        log.info("商场版销售");
        MallGoods mallGoods = new MallGoods();
        for (int i = 0; i < 2; i++) {
            Thread thread = new Thread(mallGoods, "商场销售员-" + i);
            thread.start();
        }
        log.info("{} 运行结束", ThreadUtil.getCurThreadName());
    }
}
